package com.xqls.thread;

import com.xqls.server.dto.SoketCommonDto;
import com.xqls.server.netty.future.SyncWriteFuture;
import com.xqls.server.netty.future.SyncWriteMap;
import com.xqls.server.netty.future.WriteFuture;
import org.apache.log4j.Logger;

import java.util.concurrent.Callable;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 等待操作结果
 */
public class SoketWaitCallable implements Callable<Void> {
    private static Logger logger = Logger.getLogger(SoketWaitCallable.class);
    private final CyclicBarrier barrier;
    private  StringBuffer resultMsg;
    private AtomicBoolean success;
    private  String deviceNo;
    private  Boolean isSampling;//是否为采样仪启动状态 不是的话为阀门角度
    private Integer value;
    public SoketWaitCallable( CyclicBarrier barrier,
                             StringBuffer resultMsg, AtomicBoolean success, String deviceNo, Boolean isSampling, Integer value) {
        this.barrier = barrier;
        this.success=success;
        this.resultMsg=resultMsg;
        this.deviceNo=deviceNo;
        this.isSampling=isSampling;
        this.value=value;
    }



    @Override
    public Void call() throws Exception {
        try {
            //waitType
            // 发送数据到客户端
            final WriteFuture<SoketCommonDto> writeFuture = new SyncWriteFuture(deviceNo,value);
            int waitTime=60000;
          if(isSampling){
              SyncWriteMap.waitSamplingResponses.put(writeFuture.requestId(), writeFuture);
          }else {
              waitTime=waitTime*3;
              SyncWriteMap.waitValueResponses.put(writeFuture.requestId(), writeFuture);
          }
            SoketCommonDto response = writeFuture.get(waitTime, TimeUnit.MILLISECONDS);//等待60000毫秒
            if(isSampling){
                SyncWriteMap.waitSamplingResponses.put(writeFuture.requestId(), writeFuture);
            }else {
                SyncWriteMap.waitValueResponses.put(writeFuture.requestId(), writeFuture);
            }
            if(response ==null){
                if(success.compareAndSet(true,true)){
                        success.set(false);
                    resultMsg.append(deviceNo+"等待结果异常").append("<br> ");
                }
            }
            barrier.await();
        } catch ( Exception e) {
            logger.error("等待结果异常",e);
            resultMsg.append( "等待结果异常<br> ");
            success.set(false);
        }

        return null;
    }
}
